

/**
 * @description 迭代一个对象
 */
export function jsonEach<
  O extends object = Dict,
  K extends keyof O = keyof O,
  V extends O[K] = O[K],
  E extends (k: K, v: V) => void = (k: K, v: V) => void
>(objects: O, each: E) {
  Object.keys(objects).forEach((key) => {
    each(key as K, objects[key] as V);
  });
}

/**
  * @description 如果list不是数组，返回空数组
  * @param list 可能为数组的对象
  * @param end 结束位置
  * @param start 开始位置，默认为0
  * @returns 始终返回一个数组
*/
export function slice<T = unknown>(list: unknown, end: number, start = 0): T[] {
  if (Array.isArray(list)) {
    return list.slice(start, end);
  }
  return [];
}

/**
 * @description 对一个数组过滤掉所有的空值 { null, undefined}
 * @param list 
 * @returns list
 */
export function filterNil<T extends Array<unknown> = Array<unknown>>(list: T): NonNullable<T> {
  return list.filter(el => el !== null && typeof el !== "undefined") as NonNullable<T>;
}

/* eslint-disable no-undefined */
export function filterNilInJson<T extends Dict<null | undefined | unknown> = Dict>(objects: T) {
  /* eslint-disable  eqeqeq */
  return Object.keys(objects).reduce((model, key) => objects[key] == null ? model : (model[key] = objects[key], model), {}) as T;
}

export const shallowMerge = Object.assign;
